package dk.twu.analyzer.loader;

import dk.twu.analyzer.model.Country;
import dk.twu.analyzer.model.Currency;
import dk.twu.analyzer.model.Exchange;
import org.w3c.dom.Document;
import org.w3c.dom.NamedNodeMap;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import java.io.File;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

public class ExchangeLoader {
    public static Map<String, Exchange> loadExchangeMap(String baseDir, String exchangeListFile) {
        Map<String, Exchange> exchangeList = new HashMap<>();
        File file = new File(baseDir + exchangeListFile);
        DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance();
        DocumentBuilder documentBuilder = null;
        Document document = null;
        try {
            documentBuilder = documentBuilderFactory.newDocumentBuilder();
            document = documentBuilder.parse(file);
        } catch (ParserConfigurationException e) {
            e.printStackTrace();
        } catch (SAXException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        document.getDocumentElement().normalize();
        NodeList nodeLst = document.getElementsByTagName("EXCHANGE");
        for (int idx = 0; idx < nodeLst.getLength(); idx++) {
            Node fstNode = nodeLst.item(idx);
            NamedNodeMap attributeMap = fstNode.getAttributes();
            String code = attributeMap.getNamedItem("Code").getNodeValue();
            String name = attributeMap.getNamedItem("Name").getNodeValue();
            String country = attributeMap.getNamedItem("Country").getNodeValue();
            String currency = attributeMap.getNamedItem("Currency").getNodeValue();
            String isIntraDay = attributeMap.getNamedItem("IsIntraday").getNodeValue();
            exchangeList.put(code, new Exchange(code, name, Country.valueOf(country), currency != null && currency !=
                    "" ? Currency.valueOf(currency) : Currency.UNKNOWN, Boolean.valueOf(isIntraDay)));
        }
        return exchangeList;
    }
}
